package com.naizhuai.ui.mianbusiness.action;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.naizhuai.Model.AccountHelper;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.ui.adapter.business.ActionMainCurrentAdapterHolder;
import com.naizhuai.ui.adapter.business.ActionMainWaitAdapterHolder;
import com.naizhuai.ui.entity.mainbusiness.ActionBaseBean;
import com.naizhuai.ui.entity.mainbusiness.ActionMainBean;
import com.naizhuai.ui.entity.mainbusiness.ActionShowMainItemBean;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.ui.fragment.BaseLazyFragment;
import com.naizhuai.ui.mianbusiness.action.presenter.ActionManageApiStoreIml;
import com.naizhuai.ui.mianbusiness.setting.PersonRadarActivity;
import com.naizhuai.ui.task.ActionSetting1Activity;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ErrorViewCreateUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.NaizhuAILog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Observer;
import rx.Subscription;

/**
 * 行动的主頁面
 * Created by code_han on 2018/3/22.
 */

public class ActionMainLazyFragment extends BaseLazyFragment implements ActionMainCurrentAdapterHolder.OnItemClickListener, ActionMainWaitAdapterHolder.OnItemClickListener {

    public static final int CURRENT_ACTION = 1001;
    public static final int PERSONAL_ACTION = 1002;

    @BindView(R.id.current_action_list)
    RecyclerView currentRecy;
    @BindView(R.id.personal_action_list)
    RecyclerView personalRecy;
    @BindView(R.id.wait_public_list)
    RecyclerView waitPublicRecy;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.active_score)
    TextView activeScore;

    @BindView(R.id.current_action_card)
    CardView currentCard;
    @BindView(R.id.personal_action_card)
    CardView personalCard;
    @BindView(R.id.wait_action_card)
    CardView waitCard;

    @BindView(R.id.current_action_number)
    TextView currentNumber;
    @BindView(R.id.personal_action_number)
    TextView personalNumber;
    @BindView(R.id.wait_action_number)
    TextView waitNumber;

    @BindView(R.id.error_content)
    RelativeLayout errorLayout;

    private List<ActionShowMainItemBean> currentActionList;
    private List<ActionShowMainItemBean> personalActionList;
    private List<ActionShowMainItemBean> waitPublicActionList;
    private ActionMainCurrentAdapterHolder currentAdapter;
    private ActionMainCurrentAdapterHolder personalAdapter;
    private ActionMainWaitAdapterHolder waitAdapter;

    private Subscription requestSub;

    public static ActionMainLazyFragment newInstance() {
        ActionMainLazyFragment fragment = new ActionMainLazyFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView(View view) {
        initBaseData();
        initBasicView();
        initRecyclerView();
//        refreshLayout.autoRefresh();
//        requestData();
    }


    @Override
    public void onResume() {
        super.onResume();
        requestData();
    }

    private void initBasicView() {
        initErrorLayout();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
//                shortToast("setOnRefreshListener");
                requestData();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //获取更多的代接榜
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.finishLoadmore();
                    }
                }, 1000);
            }
        });
    }

    private void initErrorLayout() {
        errorLayout.setVisibility(View.VISIBLE);
        errorLayout.removeAllViews();
        errorLayout.addView(ErrorViewCreateUtils.createLoadingView(getActivity()));
    }

    private void requestData() {
        requestSub = ActionManageApiStoreIml.getInstance().getActionMainPager(getShareValue(CompanyBean.COMPANY_ID_KEY, "")).subscribe(new Observer<ActionMainBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ApiException.showException(e, getActivity());
                if (errorLayout == null)
                    return;
                errorLayout.setVisibility(View.VISIBLE);
                errorLayout.removeAllViews();
                errorLayout.addView(ErrorViewCreateUtils.createNoNetworkView(getActivity(), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initErrorLayout();
                        requestData();
                    }
                }));
                if (refreshLayout.isLoading()) {
                    refreshLayout.finishRefresh();
                }
            }

            @Override
            public void onNext(ActionMainBean actionMainBean) {
                if (refreshLayout == null)
                    return;
                if (refreshLayout.isRefreshing()) {
                    refreshLayout.finishRefresh();
                    shortToast(getText(R.string.refresh_ok).toString());
                }
                if (actionMainBean.getOnGoingCompanyQuestionList().size() == 0 && actionMainBean.getOnGoingPersonalQuestionList().size() == 0
                        && actionMainBean.getCompanyRecommendQuestionList().size() == 0) {
                    errorLayout.setVisibility(View.VISIBLE);
                    errorLayout.removeAllViews();
                    errorLayout.addView(ErrorViewCreateUtils.createEmptyView(getActivity()));
                    return;
                }
                errorLayout.setVisibility(View.INVISIBLE);
                String strFormat = getText(R.string.action_number).toString();
                activeScore.setText(Html.fromHtml(actionMainBean.getVitality().message));

                currentActionList.clear();
                currentActionList.addAll(actionMainBean.getOnGoingCompanyQuestionList());
                currentAdapter.notifyDataSetChanged();
                if (actionMainBean.getOnGoingCompanyQuestionList().size() > 0) {
                    currentNumber.setText(String.format(strFormat, actionMainBean.getOnGoingCompanyQuestionList().size() + ""));
                    currentCard.setVisibility(View.VISIBLE);
                } else
                    currentCard.setVisibility(View.GONE);

                personalActionList.clear();
                personalActionList.addAll(actionMainBean.getOnGoingPersonalQuestionList());
                personalAdapter.notifyDataSetChanged();
                if (actionMainBean.getOnGoingPersonalQuestionList().size() > 0) {
                    personalNumber.setText(String.format(strFormat, actionMainBean.getOnGoingPersonalQuestionList().size() + ""));
                    personalCard.setVisibility(View.VISIBLE);
                } else
                    personalCard.setVisibility(View.GONE);

                waitPublicActionList.clear();
                waitPublicActionList.addAll(actionMainBean.getCompanyRecommendQuestionList());
                waitAdapter.notifyDataSetChanged();
                if (actionMainBean.getCompanyRecommendQuestionList().size() > 0) {
                    waitNumber.setText(String.format(strFormat, actionMainBean.getCompanyRecommendQuestionList().size() + ""));
                    waitCard.setVisibility(View.VISIBLE);
                } else
                    waitCard.setVisibility(View.GONE);

            }
        });
    }

    public void cancelRequest() {
        if (requestSub != null && !requestSub.isUnsubscribed())
            DialogUtils.showSureDialog(getActivity(), getString(R.string.cancel_submit_request), new View.OnClickListener() {
                @Override
                public void onClick(View dialog) {
                    requestSub.unsubscribe();
                }
            });
    }

    private void initBaseData() {
        currentActionList = new ArrayList<>();
        personalActionList = new ArrayList<>();
        waitPublicActionList = new ArrayList<>();
    }


    private void initRecyclerView() {
        //当前行动的横向滑动列表
        currentAdapter = new ActionMainCurrentAdapterHolder(getActivity(), currentActionList, CURRENT_ACTION);
        currentRecy.setNestedScrollingEnabled(false);
        currentRecy.setHasFixedSize(true);
        currentRecy.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        currentRecy.setItemAnimator(new DefaultItemAnimator());
        currentRecy.setAdapter(currentAdapter);
        currentAdapter.setOnItemClickListener(this);
        //个人行为的横向滑动列表
        personalAdapter = new ActionMainCurrentAdapterHolder(getActivity(), personalActionList, PERSONAL_ACTION);
        personalRecy.setNestedScrollingEnabled(false);
        personalRecy.setHasFixedSize(true);
        personalRecy.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        personalRecy.setItemAnimator(new DefaultItemAnimator());
        personalRecy.setAdapter(personalAdapter);
        personalAdapter.setOnItemClickListener(this);
        //待揭榜的纵向滑动列表
        waitAdapter = new ActionMainWaitAdapterHolder(getActivity(), waitPublicActionList);
        waitPublicRecy.setNestedScrollingEnabled(false);
        waitPublicRecy.setHasFixedSize(true);
        GridLayoutManager layoutManage = new GridLayoutManager(getContext(), 3);
        waitPublicRecy.setLayoutManager(layoutManage);
        waitPublicRecy.setItemAnimator(new DefaultItemAnimator());
        waitPublicRecy.setAdapter(waitAdapter);
        waitAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(View view, int position, int type) {
        String actionId = null;
        String stepNumber = "1";
        switch (type) {
            case CURRENT_ACTION:
                actionId = currentActionList.get(position).getQuestionId();
                stepNumber = currentActionList.get(position).getStep();
                break;
            case PERSONAL_ACTION:
                actionId = personalActionList.get(position).getQuestionId();
                stepNumber = personalActionList.get(position).getStep();
                break;
        }
        IntentUtils.startStepActivity(stepNumber, actionId, getActivity());
//        IntentUtils.startActivityWithString(ActionBaseBean.ACTION_ID_KEY, actionId, getActivity(), ActionBrightSpotActivity.class);
    }

    @Override
    public void onGridItemClick(View view, int position) {
        IntentUtils.startActivityWithString(ActionBaseBean.ACTION_ID_KEY, waitPublicActionList.get(position).getQuestionId(), getActivity(), ActionSetting1Activity.class);
//        IntentUtils.startActivityWithString(ActionBaseBean.ACTION_ID_KEY, waitPublicActionList.get(position).getQuestionId(), getActivity(), ActionBrightSpotActivity.class);
    }

    @Override
    protected void onIsNotVisible() {

    }

    @Override
    protected void lazyLoad() {

    }


    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_action_main_layout;
    }


    @OnClick(R.id.current_vitality)
    public void onClickedVitality() {
        Intent intent = new Intent(getActivity(), PersonRadarActivity.class);
        intent.putExtra(PersonUserBean.USER_ID_KEY, AccountHelper.getUid());
        getActivity().startActivity(intent);
    }

}